<?php

declare(strict_types=1);
/**
 * 创建人 : Forpastime
 *
 * @link     http://hypercmf.com
 * @document https://hyperf.wiki
 * @contact  forpastime@qq.com
 * @git  https://gitee.com/hypercmf/hypercmf1.0.git
 */
namespace App\Controller\Admin;

use App\Controller\AdminBaseController;
use App\Model\Role;
use App\Service\AdminService;
use App\Utils\Result;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;

/**
 * @AutoController
 */
#[AutoController]
class IndexController extends AdminBaseController
{
    public function home()
    {
        $composer = file_get_contents('./composer.json');
        $composer = json_decode($composer,true);
        return $this->fetch('admin/home',['devtool'=>$composer['require-dev']]);
    }

    /**
     * @var RequestInterface
     * @Inject()
     */
    protected $request;

    /**
     * @var AdminService
     * @Inject()
     */
    protected $adminService;
    /**
     * @var Role
     * @Inject()
     */
    protected $role;

    public function heart()
    {
        $token = $this->request->getHeader('token');
        if (! empty($token[0])) {
            // 接口鉴权
            $info = explode('_',$token[0]);
            $redis = for_redis_pool();
            if(!$redis->get('HyperCMF:admin_token:'.$info[0]) || $redis->get('HyperCMF:admin_token:'.$info[0]) != $info[1]){
                return Result::error('登录已过期',-1);
            }
        }
        return Result::success();
    }

    public function loadMenu()
    {
        $token = $this->request->getHeader('token');
        if (! empty($token[0])) {
            // 接口鉴权
            $info = explode('_',$token[0]);
            $redis = for_redis_pool();
            if(!$redis->get('HyperCMF:admin_token:'.$info[0]) || $redis->get('HyperCMF:admin_token:'.$info[0]) != $info[1]){
                return Result::error('登录已过期',-1);
            }
            $roleId = $this->adminService->getUser([['user_name','=',$info[0]]],'role_id');
            $cache = $redis->get('HyperCMF:role_menu_data:'.$roleId['role_id']);
            if($cache){
                $menu = for_prepare_menu(json_decode($cache,true));
            }else{
                $nodes = $this->role->getOneRole($roleId['role_id']);
                $menuData = $this->adminService->getMenu($nodes['rule']);
                $redis->set('HyperCMF:role_menu_data:'.$roleId['role_id'],json_encode($menuData->toArray()));
                $menu = for_prepare_menu($menuData);
            }
        }
        return Result::success($menu);
    }
}
